<template>
  <div class="crk-report">
    <div class="toolbar">
      <el-radio-group v-model="quickRange" size="small" @change="onQuickRange">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="today">今日</el-radio-button>
        <el-radio-button label="yesterday">昨日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="custom">自定义</el-radio-button>
      </el-radio-group>
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        :disabled="quickRange !== 'custom'"
        style="margin-left:12px;width: 420px"
      />
      <el-input v-model="query.goodsOrCategory" placeholder="物品/类别" style="width:160px;margin-left:12px" clearable />
      <el-input v-model="query.operatorName" placeholder="经办人/制单人" style="width:180px;margin-left:12px" clearable />
      <el-button type="primary" style="margin-left:12px" @click="loadData(1)">查询</el-button>
      <el-button @click="reset">重置</el-button>
    </div>

    <div class="cards">
      <el-card class="card" shadow="never">
        <div class="num green">{{ stats.inboundQuantity }}</div>
        <div class="label">入库数量</div>
      </el-card>
      <el-card class="card" shadow="never">
        <div class="num green">{{ formatMoney(stats.inboundAmount) }}</div>
        <div class="label">入库金额</div>
      </el-card>
      <el-card class="card" shadow="never">
        <div class="num orange">{{ stats.outboundQuantity }}</div>
        <div class="label">出库数量</div>
      </el-card>
      <el-card class="card" shadow="never">
        <div class="num orange">{{ formatMoney(stats.outboundAmount) }}</div>
        <div class="label">出库金额</div>
      </el-card>
    </div>

    <el-table :data="tableData" border style="width: 100%" height="560">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="billNo" label="出入库单号" width="140" />
      <el-table-column prop="bizTime" label="出入库时间" width="170">
        <template #default="{ row }">{{ formatTime(row.bizTime) }}</template>
      </el-table-column>
      <el-table-column prop="bizType" label="出入库类型" width="100" />
      <el-table-column prop="goodsName" label="货品名称" min-width="160" />
      <el-table-column prop="warehouseName" label="仓库名称" width="140" />
      <el-table-column prop="warePlaceName" label="库位名称" width="120" />
      <el-table-column prop="inUnitPrice" label="入库单价" width="100">
        <template #default="{ row }">{{ row.inUnitPrice !== null ? formatMoney(row.inUnitPrice) : '—' }}</template>
      </el-table-column>
      <el-table-column prop="inQuantity" label="入库数量" width="100" />
      <el-table-column prop="inAmount" label="入库金额" width="120">
        <template #default="{ row }">{{ row.inAmount !== null ? formatMoney(row.inAmount) : '—' }}</template>
      </el-table-column>
      <el-table-column prop="outUnitPrice" label="出库单价" width="100">
        <template #default="{ row }">{{ row.outUnitPrice !== null ? formatMoney(row.outUnitPrice) : '—' }}</template>
      </el-table-column>
      <el-table-column prop="outQuantity" label="出库数量" width="100" />
      <el-table-column prop="outAmount" label="出库金额" width="120">
        <template #default="{ row }">{{ row.outAmount !== null ? formatMoney(row.outAmount) : '—' }}</template>
      </el-table-column>
      <el-table-column prop="operatorName" label="经办人" width="100" />
      <el-table-column prop="makerName" label="制单人" width="100" />
      <el-table-column prop="deptName" label="所在部门" width="100" />
      <el-table-column prop="makeTime" label="制单时间" width="170">
        <template #default="{ row }">{{ row.makeTime ? formatTime(row.makeTime) : '—' }}</template>
      </el-table-column>
      <el-table-column prop="auditorName" label="审核人" width="100" />
      <el-table-column prop="auditTime" label="审核时间" width="170">
        <template #default="{ row }">{{ row.auditTime ? formatTime(row.auditTime) : '—' }}</template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="160" />
    </el-table>

    <div class="pager">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        v-model:current-page="page"
        v-model:page-size="pageSize"
        @size-change="loadData(1)"
        @current-change="loadData"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { ref, reactive, watch } from 'vue'
import { fetchInOutFlowPage, fetchInOutFlowStats, type GetInOutFlowInput } from '/@/api/report/crk'

const tableData = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

const quickRange = ref<'all'|'today'|'yesterday'|'week'|'month'|'custom'>('month')
const dateRange = ref<[string, string] | null>(null)

const query = reactive<{ goodsOrCategory?: string; operatorName?: string }>({})

function computeRange() {
  const now = dayjs()
  switch (quickRange.value) {
    case 'all':
      return null
    case 'today':
      return [now.startOf('day').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'yesterday': {
      const y = now.subtract(1, 'day')
      return [y.startOf('day').format('YYYY-MM-DD HH:mm:ss'), y.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    }
    case 'week':
      return [now.startOf('week').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'month':
      return [now.startOf('month').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    default:
      return dateRange.value ?? null
  }
}

function buildPayload(p = page.value): GetInOutFlowInput {
  const range = computeRange()
  return {
    startTime: range ? range[0] : undefined,
    endTime: range ? range[1] : undefined,
    goodsOrCategory: query.goodsOrCategory,
    operatorName: query.operatorName,
    page: p,
    pageSize: pageSize.value
  }
}

function unwrapResponse(res: any) {
  // 优先从 result 读取，其次读取 data 本身
  return res?.data?.result ?? res?.data ?? {}
}

async function loadStats() {
  const res = await fetchInOutFlowStats(buildPayload(1))
  // 后端为 PascalCase，做兼容处理；并兼容 result 包裹
  const d: any = unwrapResponse(res)
  stats.inboundQuantity = d.InboundQuantity ?? d.inboundQuantity ?? 0
  stats.outboundQuantity = d.OutboundQuantity ?? d.outboundQuantity ?? 0
  stats.inboundAmount = d.InboundAmount ?? d.inboundAmount ?? 0
  stats.outboundAmount = d.OutboundAmount ?? d.outboundAmount ?? 0
}

async function loadData(p?: number) {
  if (p) page.value = p
  const res = await fetchInOutFlowPage(buildPayload(page.value))
  const d: any = unwrapResponse(res)
  const list = (d.items || d.Items || []) as any[]
  // 将后端 PascalCase 字段转为前端使用的 camelCase
  tableData.value = list.map((i: any) => ({
    // 基础字段
    bizType: i.bizType ?? i.BizType,
    billNo: i.billNo ?? i.BillNo,
    bizTime: i.bizTime ?? i.BizTime,
    goodsName: i.goodsName ?? i.GoodsName,
    warehouseName: i.warehouseName ?? i.WarehouseName,
    warePlaceName: i.warePlaceName ?? i.WarePlaceName,
    operatorName: i.operatorName ?? i.OperatorName,
    remark: i.remark ?? i.Remark,
    // 扩展为图片上的字段（若后端无则为 null）
    inUnitPrice: i.inUnitPrice ?? i.InUnitPrice ?? null,
    inQuantity: i.inQuantity ?? i.InQuantity ?? (i.bizType === '入库' ? (i.quantity ?? i.Quantity ?? null) : null),
    inAmount: i.inAmount ?? i.InAmount ?? (i.bizType === '入库' ? (i.amount ?? i.Amount ?? null) : null),
    outUnitPrice: i.outUnitPrice ?? i.OutUnitPrice ?? null,
    outQuantity: i.outQuantity ?? i.OutQuantity ?? (i.bizType === '出库' ? (i.quantity ?? i.Quantity ?? null) : null),
    outAmount: i.outAmount ?? i.OutAmount ?? (i.bizType === '出库' ? (i.amount ?? i.Amount ?? null) : null),
    makerName: i.makerName ?? i.MakerName ?? null,
    deptName: i.deptName ?? i.DeptName ?? null,
    makeTime: i.makeTime ?? i.MakeTime ?? null,
    auditorName: i.auditorName ?? i.AuditorName ?? null,
    auditTime: i.auditTime ?? i.AuditTime ?? null,
  }))
  total.value = d.total || d.Total || 0
  await loadStats()
}

function onQuickRange() {
  if (quickRange.value !== 'custom') {
    loadData(1)
  }
}

function reset() {
  quickRange.value = 'today'
  query.goodsOrCategory = undefined
  query.operatorName = undefined
  dateRange.value = null
  loadData(1)
}

const stats = reactive({
  inboundQuantity: 0,
  outboundQuantity: 0,
  inboundAmount: 0,
  outboundAmount: 0
})

function formatMoney(n: number) {
  return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY', maximumFractionDigits: 2 }).format(n || 0)
}

function formatTime(t: string | Date) {
  if (!t) return ''
  const d = typeof t === 'string' ? new Date(t) : t
  return dayjs(d).format('YYYY-MM-DD HH:mm:ss')
}

watch(pageSize, () => loadData(1))

loadData(1)
</script>

<style scoped>
.crk-report { padding: 12px; }
.toolbar { display: flex; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
.cards { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 12px; }
.card { text-align: center; }
.num { font-size: 22px; font-weight: 700; }
.num.green { color: #18a058; }
.num.orange { color: #f0a020; }
.label { color: #888; margin-top: 4px; font-size: 12px; }
.pager { margin-top: 10px; display: flex; justify-content: flex-end; }
</style>


